﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing.Fields;
using Microsoft.SharePoint.Taxonomy;

namespace E4D.Solutions.SPRNuGet.WebServiceDefinition.Entities
{
    public class NugetPackagesContainer
    {
        private List<NugetEntity> packs = new List<NugetEntity>();

        public NugetPackagesContainer()
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.RootWeb)
                {
                    SPList list = (from SPList x in web.Lists where x.ContentTypes[0].Name == "SPRNuGet Content Type" select x).FirstOrDefault();
                    if (list != null)
                    {
                        foreach (SPListItem item in list.Items)
                        {
                            packs.Add(new NugetEntity()
                            {
                                Authors = item["Author"].ToString().Split('#')[1],
                                Copyright = item["NugCopyright"]!=null ? item["NugCopyright"].ToString() : string.Empty,
                                Dependencies ="",
                                Description = item["NugDescription"] != null ? item["NugDescription"].ToString() : string.Empty,
                                DownloadCount = item["NugDownload"]!=null ? Convert.ToInt32(item["NugDownload"].ToString()) : 0,
                                FullPath =  item.File.Item[SPBuiltInFieldId.EncodedAbsUrl].ToString(),
                                Version = item["NugVersion"].ToString(),
                                Id = item["ID"].ToString(),
                                Title = item["NugTitle"].ToString(),
                                PackageHashAlgorithm = item["NugHashAlgo"].ToString(),
                                PackageHash = item["NugHash"].ToString(),
                                PackageSize = Convert.ToInt64(item["NugPackSize"].ToString()),
                                Published = Convert.ToDateTime(item["Created"].ToString()),
                                LastUpdated = Convert.ToDateTime(item["Modified"].ToString()),
                                IsLatestVersion = Convert.ToBoolean(item["NugLastVersion"].ToString()),
                                Created = Convert.ToDateTime(item["Created"].ToString()),
                                //IconUrl = item["NugIcon"] != null ? (item["NugIcon"] as ImageFieldValue).ImageUrl : string.Empty,
                                IconUrl = item["NugIcon"] != null ? site.MakeFullUrl((item["NugIcon"] as ImageFieldValue).ImageUrl) : string.Empty,
                                IsAbsoluteLatestVersion = Convert.ToBoolean(item["NugAbsLastVersion"].ToString()),
                                LicenseUrl=item["NugLicenseUrl"]!=null ? item["NugLicenseUrl"].ToString().Split(',')[0] : string.Empty,
                                ProjectUrl=item["NugProjectUrl"]!= null ? item["NugProjectUrl"].ToString().Split(',')[0] : string.Empty,
                                ReleaseNotes=item["NugReleaseNotes"]!=null ? item["NugReleaseNotes"].ToString() : string.Empty,
                                RequireLicenseAcceptance=Convert.ToBoolean(item["NugRequireLicenseAcceptance"].ToString()),
                                Summary=item["NugSummary"]!=null ? item["NugSummary"].ToString() : string.Empty,
                                Tags=item["NugTags"]!=null ? GetTaxonomyValues(item["NugTags"] as TaxonomyFieldValueCollection) : string.Empty,
                                VersionDownloadCount=0,
                            });

                        }
                    }
                }
            }
        }

        public IQueryable<NugetEntity> Packages
        {
            get { return packs.AsQueryable(); }
        }

        #region helper methods
        private static string GetTaxonomyValues(TaxonomyFieldValueCollection taxField)
        {
            string tags = "";
            var valuesList = (from t in taxField select t.Label).ToList();
            foreach (var tag in valuesList)
            {
                tags += tag + ", ";
            }
            if (tags.Length > 2)
                tags = tags.Remove(tags.LastIndexOf(','));
            return tags;
        }
        #endregion
    }
}
